package com.bjypc.youth.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class RelatedSpecialData {
	public RelatedSpecialData() {

	}

	public static void main(String[] argv) {
		String folder = "D:\\temp\\articles";
		String writeJs = "D:\\workplaces\\struts2\\bjyouth\\WebRoot\\js\\relatedResearchData.js";
		String dataJs = "D:\\workplaces\\struts2\\bjyouth\\WebRoot\\pages\\relatedResearchData\\data.js";
		// scan
		File file = new File(folder);
		File[] filesList = file.listFiles();
		List<String> lines = new ArrayList<String>();
		String begin = "var researchArticles=[";
		lines.add(begin);
		int i = 0;
		StringBuffer articlesBuf = new StringBuffer();
		for (File subFolder : filesList) {
			if (subFolder.isDirectory()) {
				String name = subFolder.getName();
				String template = "{'href':'#','text':'"
						+ name
						+ "','id':'"
						+ name
						+ "','isClass':true,'iconCls':'icon-static','cls':'cls','leaf':true},";

				lines.add(template);
				i++;
				// parse each articles into array
				String articlesArray = parseArticle(subFolder, i);
				articlesBuf.append(articlesArray).append("\n");
			}
		}
		String end = "]";
		lines.add(end);
		try {
			//FileUtils.writeLines(new File(writeJs), "utf-8", lines, "\n");
			FileUtils.writeStringToFile(new File(dataJs), articlesBuf
					.toString(), "utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String parseArticle(File subFolder, int i) {
		StringBuffer buf = new StringBuffer();
		String begin = "var myData" + i + "=[";
		buf.append(begin).append("\n");
		File[] articles = subFolder.listFiles();
		for (File article : articles) {
			String name = article.getName();
			int index = name.indexOf(".doc");
			String title = "";
			if (index != -1) {
				title = name.substring(0, index);
			}
			String tmp = "['" + name + "','" + title
					+ "',0.02,0.03,'9/1 12:00am'],";
			buf.append("\t").append(tmp).append("\n");
		}
		String end = "];";
		buf.append(end).append("\n");
		return buf.toString();
	}
}
